package web.common.internal.jdo.sql;

import web.common.core.util.NumberUtil;
import web.common.core.util.StringUtil;
import web.common.internal.jdo.parser.DefaultSqlItem;
import web.common.jdo.exception.JdbcException;
import web.common.jdo.parser.SqlItem;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jin Zheng
 * @since 1.0 2021-12-16
 */
public class IncSqlHandler implements SqlHandler {
	public IncSqlHandler() {
	}

	@Override
	public SqlItem sql(SqlParam param) {
		var config = param.getEntityConfig();
		var map = param.getMap();
		this.checkMap(map);

		var columnMap = config.getColumnMap();
		List<String> columnList = new ArrayList<>();
		List<String> fieldList = new ArrayList<>();

		for (var entry : map.entrySet()) {
			var column = this.getColumn(entry.getKey(), columnMap);
			if (!NumberUtil.isNumber(column.getBeanField().getField().getType())) {
				throw new JdbcException("Field [" + entry.getKey() + "] is not number");
			}
			if (!NumberUtil.isNumber(entry.getValue().getClass())) {
				throw new JdbcException("Parameter [" + entry.getKey() + "] is not number");
			}
			columnList.add(column.getEscapeColumnName() + "=" + column.getEscapeColumnName() + "+?");
			fieldList.add(entry.getKey());
		}

		var id = config.getIdConfig();
		var whereId = id.getEscapeColumnName() + EQUAL_PLACEHOLDER;
		fieldList.add(id.getFieldName());

		var sql = String.format(UPDATE_TPL, config.getEscapeTableName(),
				StringUtil.join(columnList, SEPARATOR), whereId);
		return new DefaultSqlItem(sql, fieldList);
	}
}
